var fault_type = ['其他故障', '漆泡', '擦花', '喷流', '锈蚀', '脏点', '桔皮', '正常']

function print_fault(data) {
    var chartDom = document.getElementById('falutprint');
    var myChart = echarts.init(chartDom);
    data = Object.values(data.faults).concat([data.normal]);
    var total = data[0] + data[1] + data[2] + data[3] + data[4] + data[5] + data[6];
    total = total.toFixed(2);
    for(var i = 0; i < 8; ++i){
        data[i] = data[i].toFixed(2);
    }
    var option = {
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            data: fault_type
        },
        series: [
            {
                name: 'product quality',
                type: 'pie',
                selectedMode: 'single',
                radius: [0, '30%'],
                label: {
                    position: 'inner',
                    fontSize: 14
                },
                labelLine: {
                    show: false
                },
                data: [
                    { value: data[7], name: '正常' },
                    { value: total, name: '缺陷', selected: true}
                ]
            },
            {
                name: '缺陷类型',
                type: 'pie',
                radius: ['45%', '60%'],
                labelLine: {
                    length: 30
                },
                label: {
                    formatter: '{a|{a}}{abg|}\n{hr|}\n  {b|{b}：}{c}  {per|{d}%}  ',
                    backgroundColor: '#F6F8FC',
                    borderColor: '#8C8D8E',
                    borderWidth: 1,
                    borderRadius: 4,
                    rich: {
                        a: {
                            color: '#6E7079',
                            lineHeight: 22,
                            align: 'center'
                        },
                        hr: {
                            borderColor: '#8C8D8E',
                            width: '100%',
                            borderWidth: 1,
                            height: 0
                        },
                        b: {
                            color: '#4C5058',
                            fontSize: 14,
                            fontWeight: 'bold',
                            lineHeight: 33
                        },
                        per: {
                            color: '#fff',
                            backgroundColor: '#4C5058',
                            padding: [3, 4],
                            borderRadius: 4
                        }
                    }
                },
                data: [
                    { value: data[0], name: fault_type[0] },
                    { value: data[1], name: fault_type[1] },
                    { value: data[2], name: fault_type[2] },
                    { value: data[3], name: fault_type[3] },
                    { value: data[4], name: fault_type[4] },
                    { value: data[5], name: fault_type[5] },
                    { value: data[6], name: fault_type[6] }
                ]
            }
        ]
    };
    myChart.setOption(option);
}


function fetchPredictions() {
    const thresholdX = document.getElementById('thresholdInput').value;
    fetch(`/fault/draw`, {
        method: 'POST',
        headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `threshold_x=${thresholdX}`
    })
    .then(response => response.json())
    .then(data => {
        print_fault(data);
    })
    .catch(error => console.error('Error:', error));
}

// 按ID搜索功能
function searchById() {
    var searchId = $('#searchId').val();
    $.ajax({
        url: '/fault/search', // 假设服务端提供该URL
        type: 'GET',
        data: {id: searchId},
        dataType: 'json',
        success: function(data) {
            if (data.error) {
                alert(data.error);
            } else {
                var result = data[0]; 
                var table = $('#predictionsTable');
                var thead = table.find('thead tr');
                var tbody = table.find('tbody');

                // 清空表格
                tbody.empty();
                thead.find('th:not(:first)').remove();

                // 添加表头，确保顺序与文件中的顺序一致
                var expectedColumns = ['id', '漆泡', '擦花', '喷流', '锈蚀', '脏点', '桔皮', '正常'];
                $.each(expectedColumns, function(index, key) {
                    thead.append('<th>' + key + '</th>');
                });

                // 填充数据
                var row = $('<tr></tr>');
                row.append('<td>' + result.id + '</td>');
                $.each(expectedColumns, function(index, key) {
                    if (key !== 'id' && result[key] !== undefined) {
                        row.append('<td>' + result[key] + '</td>');
                    } else {
                        row.append('<td></td>'); 
                    }
                });
                tbody.append(row);
            }
        },
        error: function(error) {
            console.error('Error searching predictions:', error);
        }
    });
}